<template>
  <view class="order-wrapper">
    <!-- 头部 -->
    <uv-status-bar></uv-status-bar>
    <!--自定义头部 -->
    <z-navbar title="我的订单"></z-navbar>
    <view class="order-wrapper-tabs">
      <uv-tabs
        :list="params.tabList"
        lineWidth="139.535rpx"
        :current="params.current"
        lineColor="#FF7A66"
        :activeStyle="{
          color: '#000',
          fontWeight: 'bold'
        }"
        :inactiveStyle="{
          color: '#959595'
        }"
        itemStyle="width: 33.333%;box-sizing: border-box; text-align: center; padding-left: 15px; padding-right: 15px; height: 34px; color: #fff;"
        @change="onTabsChange"
      >
      </uv-tabs>
    </view>

    <view class="order-wrapper-content">
      <scroll-view scroll-y style="height: 100%" lower-threshold="100" @scrolltolower="onScrolltolower">
        <view class="box">
          <template v-if="params.list.length">
            <Card v-for="item in params.list" :key="item" class="box-item" :info="item" />
          </template>
          <view v-else class="empty-txt">---暂无数据---</view>
        </view>
      </scroll-view>
    </view>

    <uv-toast ref="toastRef"></uv-toast>

    <uv-safe-bottom></uv-safe-bottom>
  </view>
</template>

<script setup>
  import { onLeft, isTimeNull } from '@/common/js/fn';
  import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
  import { onLoad, onShow, onHide, onReady } from '@dcloudio/uni-app';
  import { ref, reactive, computed, defineProps, watch, defineExpose, getCurrentInstance } from 'vue';
  const instance = getCurrentInstance();
  const query = uni.createSelectorQuery().in(instance.proxy);
  import Card from './components/Card';
  import store from '@/store/index.js';
  let { state } = store;
  const toastRef = ref();
  const totalPage = ref(1),
    top = ref(0);
  let params = reactive({
    current: 1,
    tabList: [
      { name: '全部', value: -1 },
      { name: '待使用', value: 0 },
      { name: '已完成', value: 1 }
    ],
    query: {
      // "state": -1, //订单状态
      openid: state.vuex_openid,
      currentPage: 1,
      pageSize: 20, //每页数量
      query: '', //关键字搜索
      usageStatus: -1 //订单是否使用 -1所有，0待使用 1已使用
    },
    list: []
  });

  let httpMineCollect = async (reset = false) => {
    try {
      const res = await uni.$uv.http.post(`app/transaction/list`, params.query);

      const { hasUsed, pendingUse, pagination, transactions } = res;
      params.tabList[1].badge = {
        numberType: 'limit',
        value: pendingUse
      };
      params.tabList[2].badge = {
        numberType: 'limit',
        value: hasUsed
      };
      totalPage.value = pagination.totalPage;
      const _list = transactions.map(item => {
        let { merchant, teacher, lesson, transaction, qrcode, onlineLesson } = item;
        let { issueDate, price, issues, timeDuration } = lesson;
        lesson = { ...lesson, issueDate: dayjs(lesson.issueDate).format('YYYY-MM-DD') };
        if (!issues.length) {
          if (!isTimeNull(issueDate)) {
            let classTime = dayjs(issueDate).format('YYYY-MM-DD');
            issues = [{ classTime, timeDuration, time: classTime + ' ' + timeDuration, address: '' }];
          }
        } else {
          issues = issues.map((r, i) => {
            let classTime = dayjs(r.classTime).format('YYYY-MM-DD');
            let times = r.timeDuration.split('-');
            let begin = dayjs().isAfter(dayjs(classTime + ' ' + times[0]), 'minute');
            let end = dayjs().isAfter(dayjs(classTime + ' ' + times[1]), 'minute');
            let state, stateName;
            if (begin && end) {
              state = 0;
              stateName = '已结束';
            } else if (!begin && !end) {
              state = 1;
              stateName = '未开始';
            } else if (begin && !end) {
              state = 2;
              stateName = '进行中';
            }
            return {
              ...r,
              classTime,
              time: classTime + ' ' + timeDuration,
              address: r.province ? r.province + r.city + r.district + r.detail : '暂无地址',
              state,
              stateName
            };
          });
        }
        // 先找进行中，没有就找未开始，如果都没有，那就取第一个
        let activeIndex = issues.findIndex(row => row.state === 2);
        if (activeIndex === -1) {
          activeIndex = issues.findIndex(row => row.state === 1);
        }
        return {
          onlineLesson,
          activeIndex: activeIndex === -1 ? 0 : activeIndex,
          lesson,
          transaction,
          merchant,
          teacher,
          price: Number(price / 100).toFixed(2),
          hasCoupon: params.query.usageStatus == 0,
          qrcode,
          qrcodeJson: JSON.stringify({ id: qrcode.timetableID, tSerial: qrcode.transactionSerial, tId: qrcode.transactionID }),
          issues,
          launch: false
        };
      });
      if (reset) {
        params.list.splice(0, params.list.length, ..._list);
      } else {
        params.list.push(..._list);
      }
    } catch (e) {
    }
  };
  // 滚动到底部触发
  const onScrolltolower = () => {
    if (params.query.currentPage >= totalPage.value) return;
    params.query.currentPage++;
    httpMineCollect();
  };
  const onTabsChange = item => {
    const { index, value } = item;
    params.current = index;
    params.query.usageStatus = value;
    httpMineCollect(true);
  };
  httpMineCollect();
  onReady(() => {
    query
      .select('.order-wrapper-content')
      .boundingClientRect(data => {
        top.value = data.top;
      })
      .exec();
  });
  let autoVideo = () => {
    ajax.list.forEach(r => {
      r.autoVideo = false;
    });
    let num = scrollActive.value;
    // 如果是竖着的，那下个也要播放
    if (['Lesson','MerchantLesson', 'Video'].includes(ajax.list[num].classify) && ['Lesson','MerchantLesson', 'Video'].includes(ajax.list[num + 1].classify)) {
      ajax.list[num + 1].autoVideo = true;
    }
    ajax.list[num].autoVideo = true;
  };
  // 滚动事件，然后加了个防抖
  const onScroll = ({ detail, active }) => {
    scrollOldTop.value = detail.scrollTop;
    scrollActive.value = active;
    autoVideo();
  };
  // 滚动到底部
  const scrolltolower = active => {
    scrollActive.value = active;
    autoVideo();
  };
</script>
<style lang="scss" scoped>
  .order-wrapper {
    overflow: hidden;
    height: 100vh;
    width: 100vw;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    &-tabs {
      box-shadow: 0px 2px 4px 0px #0000001a;
      padding-bottom: 20.93rpx;
      padding-top: 5.233rpx;
    }
    &-content {
      flex: 1;
      overflow: hidden;
      .card-wrapper:last-child {
        margin-bottom: 59rpx;
      }
    }
    .box {
      padding-top: 22.674rpx;
      .empty-txt {
        color: #cecece;
        text-align: center;
        margin-top: 20rpx;
      }
    }
  }
</style>
